package h0825;
/**
  * @description 两数相加
  * @author 不知名帅哥
  * @date 2024/8/25 22:09
  * @version 1.0
*/
public class TwoNumAdd {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(2, new ListNode(4, new ListNode(7)));
        ListNode head2 = new ListNode(5, new ListNode(6, new ListNode(4)));
        ListNode res = addTwoNumbers(head, head2);
        while (res!=null){
            System.out.println(res.val);
            res=res.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(); // 哨兵节点
        ListNode cur = dummy;
        int carry = 0;
        while (l1 != null || l2 != null || carry != 0) {
            if (l1 != null) {
                carry += l1.val;
            }
            if (l2 != null) {
                carry += l2.val;
            }
            //主要是处理进位
            cur.next=new ListNode(carry%10);
            cur=cur.next;
            carry/=10;
            if (l1!=null){
                l1=l1.next;
            }
            if (l2!=null){
                l2=l2.next;
            }
        }
        return dummy.next;
    }
}
